<template>
    <Popup ref="popupRef" :title="title" :formState="formState" :rules="rules" :addApi="savePosition" :editApi="updatePosition" @success="emits('success')">
        <template #default="{ formState }">
            <a-form-item label="职位名称" name="title">
                <a-input v-model:value="formState.title" />
            </a-form-item>

            <a-form-item label="部门" name="department_id">
                <m-form-organize-department v-model:value="formState.department_id" />
            </a-form-item>

            <a-form-item label="负责人" name="leader_id">
                <m-form-admin v-model:value="formState.leader_id" />
            </a-form-item>

            <a-form-item label="状态" name="status">
                <a-switch v-model:checked="formState.status" checked-children="启用" un-checked-children="禁用" />
            </a-form-item>
        </template>
    </Popup>
</template>

<script setup lang="ts">
import Popup from '@/components/popup/index.vue'
import { savePosition, updatePosition } from '@/api/system/organize/position'
const popupRef = ref<InstanceType<typeof Popup>>()

const mode = ref<string>('add')
const emits = defineEmits(['success'])
interface FormState {
    id: number | null,
    title: string,
    department_id: number | null,
    status: boolean,
    leader_id: number | null
}

const formState = reactive<FormState>({
    id: null,
    title: '',
    department_id: null,
    status: true,
    leader_id: null
})


const title = computed(() => {
    return mode.value === 'add' ? '新增职位' : '编辑职位'
})

const rules = {
    title: [{ required: true, message: '请输入职位名称' }],
    department_id: [{ required: true, message: '请选择部门' }],
    leader_id: [{ required: true, message: '请选择负责人' }]
}

const open = (modes: string, record?: any) => {
    mode.value = modes
    if (record) {
        for (const key in formState) {
            formState[key] = record[key]
        }
    }
    popupRef.value?.open(modes, formState)
}

defineExpose({
    open
})
</script>
